import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { FormInstance, UploadProps } from 'antd';
import { Button, Form, Input, message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/lib/upload';
import type { RcFile, UploadFile } from 'antd/lib/upload/interface';
import { useEffect, useRef, useState } from 'react';
import { getApplinksByid, updateAppLinks } from '../service';

const UpdateAppItem: React.FC<{ id: string; changeIsShowUpdate: Function }> = ({
  id = '',
  changeIsShowUpdate,
}) => {
  const formRef = useRef<FormInstance>(null);

  // const [isShow,setIsshow]=useState(false);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [imageUrl, setImageUrl] = useState<string>();
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [loading, setLoading] = useState(false);
  const beforeUpload = (file: RcFile) => {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片必须小于1MB!');
    }
    return isLt1M;
  };
  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      setImageUrl(info.file.response.data.url);
      message.success(`${info.file.name} 图片上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 图片上传失败`);
    }
  };

  const onFinish = (values: any) => {
    const data = { ...values, ...{ icon: imageUrl } };
    updateAppLinks(id, data)
      .then((res) => {
        if (res?.success == true) {
          message.success('修改成功');
          formRef.current!.resetFields();
          changeIsShowUpdate();
        } else {
          message.error('修改失败');
        }
      })
      .catch((err) => {
        message.error(err);
      });
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>点击上传图片</div>
    </div>
  );

  useEffect(() => {
    getApplinksByid(id).then((res) => {
      if (res?.success) {
        formRef.current!.setFieldsValue({
          name: res.data.name,
          links: res.data.links,
          appId: res.data.app_id,
        });
      }
    });
  }, [id]);

  return (
    <Form
      name="basic"
      onFinish={onFinish}
      colon={false}
      labelWrap={true}
      layout="vertical"
      initialValues={{ remember: true }}
      autoComplete="off"
      ref={formRef}
    >
      <Form.Item
        label="小程序名称"
        name="name"
        rules={[{ required: true, message: '请输入小程序名称' }]}
      >
        <Input placeholder="请输入" />
      </Form.Item>
      <Form.Item label="AppID" name="appId" rules={[{ required: true, message: '请输入appid' }]}>
        <Input placeholder="请输入" />
      </Form.Item>
      <Form.Item
        label="小程序链接"
        name="links"
        rules={[{ required: true, message: '请输入小程序链接' }]}
      >
        <Input placeholder="请输入" />
      </Form.Item>
      <Form.Item
        label="上传图标"
        name="icon"
        rules={[{ required: true, message: '请上传图标图片' }]}
      >
        <Upload
          name="file"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          onPreview={onPreview}
          onChange={handleChange}
          beforeUpload={beforeUpload}
          action="/api/file/upload/singleImage"
          maxCount={1}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};
export default UpdateAppItem;
